package com.sinosoft.weixin.shiro;

import com.sinosoft.weixin.db.entity.User;
import com.sinosoft.weixin.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by huzhengying on 2017/11/11.
 */
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       return null;
    }

    //认证、登陆
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
//        if(token.getPassword() == null){
//            return null;
//        }
//        String password = new String(token.getPassword());
        //校验登陆用户名密码是否正确
//        User user = userService.validateUser(token.getUsername(),password);
//        if(null != user){
//            UserPrincipal p = new UserPrincipal(user.getId(),user.getUsername(),user.getRealname());
//            return new SimpleAuthenticationInfo(p, user.getPassword(), user.getRealname());
//        }else{
//            throw new AuthenticationException("msg:用户名密码错误！");
//        }
        String workNumber = new String(token.getPassword());
        String weChatId = token.getUsername();
        if(StringUtils.isNotBlank(workNumber) && StringUtils.isNotBlank(weChatId)){
            UserPrincipal p = new UserPrincipal(weChatId,workNumber);
            return new SimpleAuthenticationInfo(p,workNumber,weChatId);
        }else {
            throw new AuthenticationException("工号与微信号校验失败！");
        }

    }

    @Override
    public String getName() {
        return getClass().getName();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
